package com.scoy.honeymei.activity.me;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.lzy.okgo.model.HttpParams;
import com.scoy.honeymei.R;
import com.scoy.honeymei.activity.home.FilmList0Activity;
import com.scoy.honeymei.adapter.CinemaListAdapter;
import com.scoy.honeymei.adapter.ShopCateCheckAdapter;
import com.scoy.honeymei.base.BaseActivity;
import com.scoy.honeymei.bean.ApplyBean;
import com.scoy.honeymei.bean.CatePlateBean;
import com.scoy.honeymei.bean.CinemaBean;
import com.scoy.honeymei.bean.OneImgBean;
import com.scoy.honeymei.http.HpCallback;
import com.scoy.honeymei.http.HpGo;
import com.scoy.honeymei.install.GlideApp;
import com.scoy.honeymei.url.ApiCallBack;
import com.scoy.honeymei.url.MeConstant;
import com.scoy.honeymei.url.MyUrl;
import com.scoy.honeymei.utils.GlideEngine;
import com.scoy.honeymei.utils.GlideImgUtil;
import com.scoy.honeymei.utils.MyUtil;
import com.scoy.honeymei.utils.SPHelper;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @ClassName: ApplyActivity$
 * @Description: 商户认证
 * @Author: GaoZhan
 * @CreateDate: 2019/9/11/0011$ 上午 10:59$
 * @UpdateUser: 更新者
 * @UpdateDate: 2019/9/11/0011$ 上午 10:59$
 * @UpdateRemark: 更新内容
 */
public class ApplyActivity extends BaseActivity {

    @BindView(R.id.back_iv)
    ImageView backIv;
    @BindView(R.id.title_tv)
    TextView titleTv;
    @BindView(R.id.sign_tv)
    TextView signTv;
    @BindView(R.id.title_llt)
    LinearLayout titleLlt;
    @BindView(R.id.aly_realname_et)
    EditText alyRealnameEt;
    @BindView(R.id.aply_shopname_et)
    EditText aplyShopnameEt;
    @BindView(R.id.aply_idcard_iv)
    ImageView aplyIdcardIv;
    @BindView(R.id.aply_door_iv)
    ImageView aplyDoorIv;
    @BindView(R.id.aply_busness_iv)
    ImageView aplyBusnessIv;
    @BindView(R.id.aply_food_iv)
    ImageView aplyFoodIv;
    @BindView(R.id.aply_reason_tv)
    TextView aplyReasonTv;
    @BindView(R.id.aply_ok_tv)
    TextView aplyOkTv;
    @BindView(R.id.aply_sign_iv)
    ImageView aplySignIv;
    @BindView(R.id.aply_cate_rv)
    RecyclerView aplyCateRv;
    private ApplyActivity mContext;
    private String checkstatus;
    private String img0;
    private String img1;
    private String img2;
    private String img3;
    private ShopCateCheckAdapter hAdapter;
    private ArrayList<Integer> shopIdList = new ArrayList<>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_apply);
        ButterKnife.bind(this);
        mContext = ApplyActivity.this;

        initNormal();

        getCate();
        httpstate();
    }

    @Override
    public void initNormal() {
        titleTv.setText(R.string.shopapply);
        MyUtil.setStatusBar(mContext, getWindow(), true, R.color.colorWhite);
        titleLlt.setPadding(0, MyUtil.getStatusBarHeight(mContext), 0, 0);

        initRv();

    }

    @OnClick({R.id.back_iv, R.id.aply_idcard_iv, R.id.aply_door_iv, R.id.aply_busness_iv, R.id.aply_food_iv, R.id.aply_ok_tv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_iv:
                finish();
                break;
            case R.id.aply_idcard_iv:
                httpUpImg(0x11);
                break;
            case R.id.aply_door_iv:
                httpUpImg(0x12);
                break;
            case R.id.aply_busness_iv:
                httpUpImg(0x13);
                break;
            case R.id.aply_food_iv:
                httpUpImg(0x14);
                break;
            case R.id.aply_ok_tv:
                if (MyUtil.isFastClick()) {
                    preClick();
                }
                break;
        }
    }


    private void initRv() {

        hAdapter = new ShopCateCheckAdapter(mContext);
        aplyCateRv.setLayoutManager(new LinearLayoutManager(mContext, RecyclerView.HORIZONTAL, false));
        aplyCateRv.setAdapter(hAdapter);
      /*  hAdapter.setOnOneClick(pos -> {
            CatePlateBean mBean = hAdapter.getItem(pos);
            Intent intentde = new Intent(mContext, FilmList0Activity.class);
            intentde.putExtra("cinemaId", mBean.getId());
            startActivity(intentde);
        });
*/
    }

    /**
     * 选择图片
     */
    private void httpUpImg(int reCode) {
        PictureSelector.create(mContext)
                .openGallery(PictureMimeType.ofImage())
                .loadImageEngine(GlideEngine.createGlideEngine())
                .maxSelectNum(1)
                .imageSpanCount(3)
                .isCamera(true)
                .enableCrop(false)
                .imageFormat(PictureMimeType.PNG)
                .compress(true)
                .minimumCompressSize(100)
                .withAspectRatio(1, 1)
                .rotateEnabled(false)
                .forResult(reCode);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 0x11://图片
                    List<LocalMedia> selectList1 = PictureSelector.obtainMultipleResult(data);
                    LocalMedia localMedia1 = selectList1.get(0);
                    String pathImg = localMedia1.getCompressPath();
                    GlideApp.with(mContext).load(new File(pathImg)).error(R.drawable.ic_nodata).into(aplyIdcardIv);

                    httpOnePic(0, localMedia1);
                    break;

                case 0x12://图片
                    List<LocalMedia> selectList2 = PictureSelector.obtainMultipleResult(data);
                    LocalMedia localMedia2 = selectList2.get(0);
                    String pathImg2 = localMedia2.getCompressPath();
                    GlideApp.with(mContext).load(new File(pathImg2)).error(R.drawable.ic_nodata).into(aplyDoorIv);
                    httpOnePic(1, localMedia2);
                    break;
                case 0x13://图片
                    List<LocalMedia> selectList3 = PictureSelector.obtainMultipleResult(data);
                    LocalMedia localMedia3 = selectList3.get(0);
                    String pathImg3 = localMedia3.getCompressPath();
                    GlideApp.with(mContext).load(new File(pathImg3)).error(R.drawable.ic_nodata).into(aplyBusnessIv);
                    httpOnePic(2, localMedia3);
                    break;
                case 0x14://图片
                    List<LocalMedia> selectList4 = PictureSelector.obtainMultipleResult(data);
                    LocalMedia localMedia4 = selectList4.get(0);
                    String pathImg4 = localMedia4.getCompressPath();
                    GlideApp.with(mContext).load(new File(pathImg4)).error(R.drawable.ic_nodata).into(aplyFoodIv);

                    httpOnePic(3, localMedia4);
                    break;
            }
        }
    }

    private void preClick() {
        if (TextUtils.isEmpty(alyRealnameEt.getText())) {
            MyUtil.mytoast(mContext, "请输入真实姓名");
            return;
        }
        if (TextUtils.isEmpty(aplyShopnameEt.getText())) {
            MyUtil.mytoast(mContext, "请输入商户名称");
            return;
        }

        if (shopIdList != null) shopIdList.clear();
        List<CatePlateBean> data = hAdapter.getData();
        for (CatePlateBean item : data) {
            if (item.getIscheck() == 1) {
                shopIdList.add(item.getId());
            }
        }
        if (shopIdList.size() == 0) {
            MyUtil.mytoast(mContext, "请选择店铺类型");
            return;
        }

        if (img0 == null || img0.length() == 0) {
            MyUtil.mytoast(mContext, "请上传身份证照");
            return;
        }
        if (img1 == null || img1.length() == 0) {
            MyUtil.mytoast(mContext, "请上传门面门头照片");
            return;
        }
        if (img2 == null || img2.length() == 0) {
            MyUtil.mytoast(mContext, "请上传营业执照");
            return;
        }
        if (img3 == null || img3.length() == 0) {
            MyUtil.mytoast(mContext, "请上传食品合格证");
            return;
        }

        httpApply();

    }

    private void httpOnePic(int tid, LocalMedia media) {

        HttpParams params = new HttpParams();
        params.put("file", new File(media.getCompressPath()));

        HpGo.newInstance().HttpGo(this, MyUrl.SINGLE_IMGUP, params, new ApiCallBack() {
            @Override
            public void onSuccess(String o) {
                OneImgBean oneImgBean = new Gson().fromJson(o, OneImgBean.class);
                if (oneImgBean.getFilePath() == null || oneImgBean.getFilePath().length() == 0) {
                    MyUtil.mytoast(mContext, "图片上传失败");
                    return;
                }
                if (tid == 0) {
                    img0 = oneImgBean.getFilePath();
                } else if (tid == 1) {
                    img1 = oneImgBean.getFilePath();
                } else if (tid == 2) {
                    img2 = oneImgBean.getFilePath();
                } else if (tid == 3) {
                    img3 = oneImgBean.getFilePath();
                }
            }

        });

    }

    //to apply
    private void httpApply() {
        HttpParams params = new HttpParams();
        params.put("userid", SPHelper.getString(MeConstant.UID, ""));
        params.put("pepole", alyRealnameEt.getText().toString());
        params.put("name", aplyShopnameEt.getText().toString());
        params.put("cardimages", img0);
        params.put("faceimages", img1);
        params.put("images", img2);
        params.put("category_ids", MyUtil.intarrToString(shopIdList));
        params.put("foodimages", img3);
        HpGo.newInstance().HttpGo(this, MyUrl.AUTHEN_TOAPPLY, params, new ApiCallBack() {
            @Override
            public void onSuccess(String o) {
                finish();
                MyUtil.mytoast0(mContext, "提交成功\n请等待审核", R.mipmap.ic_sure);
            }

        });

    }

    //获取状态
    private void httpstate() {
        HttpParams params = new HttpParams();
        params.put("userid", SPHelper.getString(MeConstant.UID, ""));
        HpGo.newInstance().HttpGo(this, MyUrl.APPLY_STATE, params, new ApiCallBack() {
            @Override
            public void onSuccess(String o) {
                ApplyBean applyBean = new Gson().fromJson(o, ApplyBean.class);
                //:0=待审核,1=审核通过,2=驳回",
                checkstatus = applyBean.getCheckstatus();
                if ("0".equals(checkstatus)) {
                    aplyOkTv.setVisibility(View.GONE);
                    aplySignIv.setImageResource(R.drawable.ic_ischecking);

                } else if ("1".equals(checkstatus)) {
                    aplyOkTv.setVisibility(View.GONE);
                    aplySignIv.setImageResource(R.drawable.ic_ispass);

                } else if ("2".equals(checkstatus)) {
                    aplyOkTv.setVisibility(View.VISIBLE);
                    aplySignIv.setImageResource(R.drawable.ic_isfail);
                    aplyReasonTv.setText("驳回原因:" + applyBean.getCheckdetail());
                }

                alyRealnameEt.setText(applyBean.getPepole());
                aplyShopnameEt.setText(applyBean.getName());
                GlideImgUtil.glidePic(mContext, applyBean.getCardimages(), aplyIdcardIv);
                GlideImgUtil.glidePic(mContext, applyBean.getFaceimages(), aplyDoorIv);
                GlideImgUtil.glidePic(mContext, applyBean.getImages(), aplyBusnessIv);
                GlideImgUtil.glidePic(mContext, applyBean.getFoodimages(), aplyFoodIv);

                img0 = applyBean.getCardimages();
                img1 = applyBean.getFaceimages();
                img2 = applyBean.getImages();
                img3 = applyBean.getFoodimages();

            }

        });

    }

    private void getCate() {
        HttpParams params = new HttpParams();
        HpGo.newInstance().HttpGo(mContext, MyUrl.CATE_PLATE, params, new ApiCallBack() {
            @Override
            public void onSuccess(String body) {
                List<CatePlateBean> mlist = new Gson().fromJson(body, new TypeToken<List<CatePlateBean>>() {
                }.getType());

                hAdapter.setNewData(mlist);

            }
        });

    }


}
